import { useNavigate } from "react-router-dom";
import type { AppRouteObject } from "#/router";
import { PERMISSION_LIST } from "@/_mock/assets";
import { flattenTrees } from "@/utils/tree";
import { createDynamicComponent } from "@/components/dynamic-wrapper";

interface NavigateOptions {
	modal?: boolean;
	callback?: () => void;
}

// 根据name获取权限信息
const getPermissionByName = (name: string) => {
	console.log("Getting permission for:", name);
	// 扁平化权限列表
	const flattenPermissions = flattenTrees(PERMISSION_LIST);
	const permission = flattenPermissions.find(
		(permission: any) => permission.name.toLowerCase() === name.toLowerCase(),
	);
	console.log("Found permission:", permission);
	return permission;
};

// 通用导航函数
export const useNavigation = () => {
	const navigate = useNavigate();

	const navigateTo = async (name: string, options?: NavigateOptions) => {
		// 获取权限信息
		const permission = getPermissionByName(name);
		if (!permission) {
			console.warn(`Permission not found for name: ${name}`);
			return null;
		}

		// 获取组件路径
		const componentPath = permission.component;
		if (!componentPath) {
			console.warn(`Component path not found for name: ${name}`);
			return null;
		}

		console.log("Navigation:", { name, componentPath, options });

		try {
			const DynamicComponent = createDynamicComponent(
				componentPath,
				permission.label,
				options?.modal,
			);

			return {
				component: DynamicComponent,
			};
		} catch (error) {
			console.error("Failed to handle navigation:", error);
			// 如果处理失败，尝试使用路由导航
			if (permission.route) {
				const path = `/${permission.route}`;
				navigate(path);
			}
			return null;
		}

		// 执行回调
		options?.callback?.();
	};

	return { navigateTo };
};
